package com.alexrnl.BetaSeriesFileManager.API.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.alexrnl.BetaSeriesFileManager.API.dao.interfaces.IShowDAO;
import com.alexrnl.BetaSeriesFileManager.API.entities.Show;

/**
 * @author Alex
 *
 */
public class ShowDAO implements IShowDAO {
	private static Logger	T	= Logger.getLogger(ShowDAO.class.getName());

	@Override
	public List<Show> searchShows (final Document doc) {
		T.fine("Parsing document for search result.");
		final List<Show> shows = new ArrayList<>();
		final Node showsList = doc.getElementsByTagName("shows").item(0);

		for (Node show = showsList.getFirstChild(); show != null;) {
			if (show.getNodeName().equals("show")) {
				String url = null, title = null;
				for (Node child = show.getFirstChild(); child != null;) {
					if (child.getNodeName().equals("url"))
						url = child.getFirstChild().getNodeValue();
					if (child.getNodeName().equals("title"))
						title = child.getFirstChild().getNodeValue();
					child = child.getNextSibling();
				}
				if (title != null && url != null) {
					T.info("Found a show (" + title + ", " + url + ").");
					shows.add(new Show(title, url));
				}
			}
			show = show.getNextSibling();
		}
		T.fine("End of parsing: found " + shows.size() + " shows matching the query.");
		return shows;
	}
}
